import * as step from '@flow-step/step-toolkit'
import * as fs from 'fs'
import {getKubernetesCertificate} from './certificate'
import {IParams} from './params'
import path from 'path'
import * as os from "os"

export async function execute(params: IParams): Promise<void> {
    const kubernetesCertificate = await getKubernetesCertificate(params)

    step.info('')
    step.info('====================================')
    step.info(`    CLUSTER TYPE ${kubernetesCertificate.type}    `)
    step.info('====================================')
    
    let kubeConfigPath = params.kubeConfigPath || `${os.homedir()}/.kube/config`
    if (kubeConfigPath.startsWith('~')) {
        // 获取用户主目录
        const homeDir = os.homedir();
        // 替换 ~ 为用户主目录
        kubeConfigPath = path.join(homeDir, kubeConfigPath.slice(1));
    }
    if (fs.existsSync(kubeConfigPath)) {
        throw new Error(`${kubeConfigPath} already exists, please remove it first`)
    }
    const dirPath = path.dirname(kubeConfigPath)
    fs.mkdirSync(dirPath, {recursive: true})

    if (kubernetesCertificate.type === 'custom' || !kubernetesCertificate.miranaProxy || kubernetesCertificate.miranaProxy === '') {
        if (kubernetesCertificate.kubeConfig === undefined || kubernetesCertificate.kubeConfig === '') {
            throw new Error('未获取到合法的Kubernetes证书文件，请检查流水线配置后再试')
        }

        fs.writeFileSync(kubeConfigPath, kubernetesCertificate.kubeConfig)
        step.debug(`kubeConfig: ${kubernetesCertificate.kubeConfig}`)
        step.info(`save kubeConfig to ${kubeConfigPath} successfully!`)
    } else {
        if (kubernetesCertificate.miranaProxy === undefined || kubernetesCertificate.jwtToken === '') {
            throw new Error('未获取到合法的ACK 证书文件，请检查流水线配置后再试')
        }
        const kubeConfigContent = `apiVersion: v1
kind: Config
clusters:
- cluster:
    server: ${kubernetesCertificate.miranaProxy}
  name: my-cluster
contexts:
- context:
    cluster: my-cluster
    user: my-user
  name: my-context
current-context: my-context
users:
- name: my-user
  user:
    token: ${kubernetesCertificate.jwtToken}`
        fs.writeFileSync(kubeConfigPath, kubeConfigContent)
        step.debug(`ack kubeConfig: ${kubeConfigContent}`)
        step.info(`save ack kubeConfig to ${kubeConfigPath} successfully!`)
    }
}